package com.cq.ssm.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cq.ssm.exception.CustomException;
import com.cq.ssm.po.Result;
import com.cq.ssm.po.User;
import com.cq.ssm.service.UserService;

@Controller
// 为了对url进行分类管理，可以在这里定义根路径，最终访问url是根路径+子路径
// 比如：商品列表：/items/queryItems.action
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	// 登陆
	@RequestMapping("/login")
	public String login(HttpSession session, String username,String password)
			throws Exception {
		// 调用service进行用户身份认证
		User u = userService.getUserByUserName(username);
		if(u==null || !u.getPassword().equals(password)){
			throw new CustomException("用户名或密码错误!");
		}
		// 在session中保存用户身份信息
		session.setAttribute("username", username);
		session.setAttribute("idStuff", username);
		session.setAttribute("userType", u.getType());
		// 重定向
		if("一级用户".equals(u.getType()))
			return "stuff/index";
		else if("三级用户".equals(u.getType()))
			return "stuffinf/stuff";
		else 
			return "index";
	}

	// 退出
	@RequestMapping("/logout")
	public String logout(HttpSession session) throws Exception {
		// 清除session
		session.invalidate();
		// 重定向到首页
		return "index";
	}

	// 修改密码
	@RequestMapping("/updatePassword")
	public @ResponseBody Result updatePassword(String username,String oldPassword,String newPassword) throws Exception{
		Result result = new Result();
		User u = userService.getUserByUserName(username);
		if(!u.getPassword().equals(oldPassword)){
			result.setMessage("原密码错误！");
		}else{
			if(userService.updatePassword(username,newPassword))
				result.setMessage("修改成功！");
			else
				result.setMessage("修改失败！");
		}
		return result;
	}
}
